<?php

namespace app\modules\api\controllers;

use app\models\ApiException;
use app\models\Package;
use app\models\Card;
use app\models\UserCardRecharge;
use app\models\UserCardReserveRecharge;
use Yii;
/**
 * 对外公开的接口
 * Class PublicController
 * @package app\modules\api\controllers
 */
class GprController extends BasePublicController
{
    public $appsecret='#EEaGHj15^s';
    public $url='http://wlwdls.rzcf.com';
    public $userid='4792';
   
    //流量池查询卡状态、到期时间和流量    
    public function actionSearch(){
        $iccid = $this->get('iccid');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $res = (new \yii\db\Query())
        ->select(['id','package_id','total_flow','data','active_time','term_end_time','status'])
        ->from('card')
        ->andFilterWhere(['like','iccid',$iccid])  
        ->all();

        $total_flow = $this->format($res[0]['total_flow']);
        $left_flow = $res[0]['data'];
        $used_flow = $this->format($left_flow);
        $left = $res[0]['total_flow'] - $left_flow;
        $left_fw = $this->format($left);
        $leftflow = $res[0]['total_flow'] - $left_flow;

        if($leftflow < 0){
            $lefts = $left_fw.'G';
            //$lefts = '流量已用尽';
            $flow = '1';
            $status = '5';
        }else{
            $lefts = $left_fw.'G';
            $status = $res[0]['status'];
            $flow = '0';
        }
        //
        $endtimes = $res[0]['term_end_time'] - time();
        if($res[0]['term_end_time'] != 0){
            if($endtimes <= 0){
                $end_time = '周期流量到期';
                $enddate = '1';
                $status = '5';
            }else{
                $end_time = date('Y-m-d H:i:s',$res[0]['term_end_time']);
                $status = $res[0]['status'];
                $enddate = '0';
            }
        }else{
            $end_time = '未充值';
            $status = $res[0]['status'];
            $enddate = '0';
        }
        
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['total_flow']=$total_flow.'G';
            $res[$key]['data'] = $used_flow.'G';
            $res[$key]['active_time']=date('Y-m-d H:i:s',$res[$key]['active_time']);
            $res[$key]['term_end_time']=$end_time;       
            $res[$key]['status'] = $res[$key]['status'];
            $res[$key]['left_flow'] = $lefts;
            $res[$key]['flow'] = $flow;
            $res[$key]['enddate'] = $enddate;

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }else{
            $data['code']="0";
            $data['msg']="无数据";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
    }
    //年包半年包查询卡状态、到期时间和流量    
    public function actionSearchYear(){
        $iccid = $this->get('iccid');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $res = (new \yii\db\Query())
        ->select(['id','package_id','total_flow','data','active_time','term_length','term_end_time','order_time','status'])
        ->from('card')
        ->andFilterWhere(['like','iccid',$iccid])  
        ->all();

        $total_flow = $this->format($res[0]['total_flow']);
        $left_flow = $res[0]['data'];
        $used_flow = $this->format($left_flow);
        $left = $res[0]['total_flow'] - $left_flow;
        $left_fw = $this->format($left);
        $leftflow = $total_flow - $left_fw;
        if($leftflow < 0){
            $lefts = '流量已用尽';
            $status = '5';
        }else{
            $lefts = $left_fw.'G';
            $status = $res[0]['status'];
        }
        
        $endtimes = $res[0]['term_end_time'] - time();
        if($res[0]['term_end_time'] != 0){
            if($endtimes <= 0){
                $end_time = '已到期';
                $active_time = '已到期';
                $status = '5';
            }else{
                $end_time = date('Y-m-d',$res[0]['term_end_time']);
                $active_time = date('Y-m-d',$res[0]['active_time']);
                $status = $res[0]['status'];
            }
        }else{
            $end_time = '未充值';
            $status = $res[0]['status'];
            $active_time = '未充值';
        }

        $package = Package::findOne(['id'=>$res[0]['package_id']]);
        if($package->length_unit == 1){
            $taocan_type = '1';
        }elseif($package->length_unit == 2){
            $taocan_type = '2';
        }elseif($package->length_unit == 3){
            $taocan_type = '3';
        }elseif($package->length_unit == 0){
            $taocan_type = '0';
        }
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['total_flow']=$total_flow.'G';
            $res[$key]['data'] = $used_flow.'G';
            $res[$key]['active_time']= $active_time;
            $res[$key]['term_end_time']=$end_time;       
            $res[$key]['status'] = $res[$key]['status'];
            $res[$key]['left_flow'] = $lefts;
            $res[$key]['order_time'] = $res[$key]['order_time'];
            $res[$key]['taocan_type'] = $taocan_type;

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
    }
    
    //根据iccid和套餐id判断联通套餐是否能充值
    public function  actionUnicom(){
        $iccid = $this->get('iccid');
        $package_id = $this->get('package_id');
        $cardresult = Card::findOne(['iccid'=>$iccid]);
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);

        if($cardresult['package_id'] == null){
            $data['code'] = '1002';
            $data['msg'] = '操作成功';
            echo json_encode($data);
            exit;
        }elseif(time() > $cardresult['term_end_time']){
            $data['code'] = '1001';
            $data['msg'] = '本月已无法充值，请下月充值';
            echo json_encode($data);
            exit;
        }elseif($packtype['type'] == '2'){
            $data['code'] = '1001';
            $data['msg'] = '次月生效套餐暂时无法充值';
            echo json_encode($data);
            exit;
        }else{
            $data['code'] = '1002';
            $data['msg'] = '操作成功';
            echo json_encode($data);
            exit;
        }        
    }

    //根据iccid和套餐判断是否可以充值
    public function  actionRecharger(){
        $conditionA = '1300';
        $conditionB = '1900';
        $iccid = $this->get('iccid');
        $package_id = $this->get('package_id');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
            $iccids = substr($iccid, 8,-8);
        }else{
            $iccids = substr($iccid, 8,-7);
        }

        $cardresult = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);
        $reserve = UserCardReserveRecharge::find()->andWhere(['card_id' => $cardresult['id']])->andWhere(['execute_status' => 2])->one();

        if($cardresult['package_id'] == null && time() > $cardresult['term_end_time']){
            if($packtype['type'] == '6'){
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
            if($packtype['type'] !='1'){
               $data['code'] = '1001';
               $data['msg'] = '首次充值请选择初始套餐!！';
               echo json_encode($data);
               exit; 
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
        }
        }elseif(time() < $cardresult['term_end_time']){
            if($package->length_unit == '12'){
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
            if($packtype['type'] != '2'){
                $data['code'] = '1001';
                $data['msg'] = '您有初始套餐,请充值叠加包';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }

        }elseif(time() > $cardresult['term_end_time']){
            if(!empty($reserve)){
                $data['code'] = '1001';
                $data['msg'] = '有未生效的预订购，请等待生效后再进行订购';
                echo json_encode($data);
                exit;
            }
            if($packtype['type'] !='1'){
               $data['code'] = '1001';
               $data['msg'] = '首次充值请选择初始套餐！';
               echo json_encode($data);
               exit; 
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
        }
        }
   
    }
    //判断年包和加油是否可以充值
    public function  actionIsRecharger(){
        $iccid = $this->get('iccid');
        $package_id = $this->get('package_id');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $cardresult = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);
        if($packtype['type'] == '3'){
            if($cardresult['term_end_time'] != '0'){
                $data['code'] = '1001';
                $data['msg'] = '您有初始套餐,请充值加油包';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
        }
        if($packtype['type'] == '2'){
            if(time() < $cardresult['term_end_time']){
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1001';
                $data['msg'] = '您尚未充值,请充值年包';
                echo json_encode($data);
                exit;
            }
        }
        
    }
    //判断年包和加油是否可以充值
    public function  actionIsRechargers(){
        $iccid = $this->get('iccid');
        $type = $this->get('type');
        $package_id = $this->get('package_id');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $cardresult = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);
        if($packtype['type'] == '4'){
            if($cardresult['term_end_time'] != '0'){
                $data['code'] = '1001';
                $data['msg'] = '您有初始套餐,请充值加油包';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
        }
        if($packtype['type'] == '5'){
            if(time() < $cardresult['term_end_time']){
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1001';
                $data['msg'] = '请充值年包';
                echo json_encode($data);
                exit;
            }
        }
        
    }    
    //根据iccid和套餐判断是否可以充值
    public function  actionRechargers(){
        $iccid = $this->get('iccid');
        $package_id = $this->get('package_id');
        $type = $this->get('type');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $cardresult = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);
        if(time() > $cardresult['term_end_time']){
            $data['code'] = '1001';
            $data['msg'] = '卡已过有效期，无法预定，请重新充值！';
            echo json_encode($data);
            exit;
        }
        if($type == '1'){
            if($cardresult['package_id'] == null){
                if($packtype['type'] !='1'){
                   $data['code'] = '1001';
                   $data['msg'] = '首次充值请选择初始套餐！';
                   echo json_encode($data);
                   exit; 
                }else{
                    $data['code'] = '1002';
                    $data['msg'] = '操作成功';
                    echo json_encode($data);
                    exit;
                }
            }else{ 
                if($packtype['type'] != '2'){

                    $data['code'] = '1001';
                    $data['msg'] = '您有初始套餐,请充值叠加包';
                    echo json_encode($data);
                    exit;
                }else{
                    $data['code'] = '1002';
                    $data['msg'] = '操作成功';
                    echo json_encode($data);
                    exit;
                } 
            }
        }
        if($type == '2'){
            if($cardresult['package_id'] == null){
                if($packtype['type'] !='1'){
                   $data['code'] = '1001';
                   $data['msg'] = '首次充值请选择初始套餐！';
                   echo json_encode($data);
                   exit; 
                }else{
                    $data['code'] = '1002';
                    $data['msg'] = '操作成功';
                    echo json_encode($data);
                    exit;
                }
            }else{ 
                if($packtype['type'] != '2'){

                    $data['code'] = '1001';
                    $data['msg'] = '您有初始套餐,请充值叠加包';
                    echo json_encode($data);
                    exit;
                }else{
                    $data['code'] = '1002';
                    $data['msg'] = '操作成功';
                    echo json_encode($data);
                    exit;
                } 
            }
        }
        if($type == '3'){
           if($cardresult['term_end_time'] == 0 || $cardresult['package_id'] == null){
                $data['code'] = '1001';
                $data['msg'] = '您尚未充值，无法预定！';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
        }
    }
    //查询充值记录
    public function actionRecharge(){
        $cardid = $this->get('iccid');
        $card = Card::findOne(['iccid'=>$cardid]);
        $list = (new \yii\db\Query())
        ->select(['recharge.id as id','money','package.name as pname','pay_time','source'])
        ->from('user_card_recharge as recharge')
        ->join('join','package','package.id=recharge.package_id')
        ->andFilterWhere(['card_id'=> $card['id']])  
        ->all();
        foreach ($list as $key=>$value){
            $list[$key]['money'] = floor($list[$key]['money']*100)/100;
            $list[$key]['pay_time'] = date('Y-m-d',$list[$key]['pay_time']);
        }
        if($list){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$list;
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];

    }
    //普通查询卡流量
    public function actionQuery(){
        $appsecrets='#EEaGHj15^s';
        $url='http://wlwdls.rzcf.com';
        $usersid='4792';
        $phone = $this->get('phone');
        if(empty($phone)){
            $data['code'] = '1002';
            $data['msg'] = '号码有误';
            $data['data'] = '';
            echo json_encode($data);
            exit;
        }
        $url = $url.'/wlw/api/query?';
        $timestamp = date('YmdHis',time());
        $noSigns =$appsecrets.$phone.$timestamp.$usersid.$appsecrets;
        $signs=md5($noSigns);
        $baseUrl = $url.'phone='.$phone.'&timestamp='.$timestamp.'&userid='.$usersid.'&sign='.$signs;
        $result = $this->getUrl($baseUrl);
        echo $result;
        exit;
    }

    public function actionSearcher(){
        $iccid = $this->get('iccid');

        $res = (new \yii\db\Query())
        ->select(['id','package_id','total_flow','data','active_time','term_length','term_end_time','status'])
        ->from('card')
        ->andFilterWhere(['iccid'=> $iccid])  
        ->all();
        
        if($res[0]['package_id'] == null){
            $result['code'] = '1001';
            $result['msg']  = '请充值';
            echo json_encode($result);
            exit;
        }

        if(time() > $res[0]['term_end_time']){
            $result['code'] = '1001';
            $result['msg']  = '周期流量到期';
            echo json_encode($result);
            exit;
        }
        $starttime = date('Ym01');
        $endTime  = date('Ymd',strtotime(date('Y-m-1',strtotime('next month')).'-1 day'));
        $url = $this->url.'/wlw/api/pool/singlequery?';
        $userid = $this->userid;
        $timestamp = date('YmdHis',time());
        $startd = $starttime;
        $endd = $endTime;
        $noSign =$this->appsecret.$endd.$iccid.$startd.$timestamp.$userid.$this->appsecret;
        $sign=md5($noSign);
        $baseUrl = $url.'&endd='.$endd.'&phone='.$iccid.'&startd='.$startd.'&timestamp='.$timestamp.'&userid='.$userid.'&sign='.$sign;
        $result = $this->getUrl($baseUrl);
        $arr = json_decode($result,true);

        $left_flow = $arr['total']*1.1;
        $total = $res[0]['total_flow']/1024/1024;
        $total_flow = $total/1024;
        $left = ($total - $left_flow)/1024;
        $left_fw = floor($left*100)/100;
        // $total_flow = $this->format($res[0]['total_flow']);
        // $left_flow = $res[0]['data']*1.1;
        $used_flow = $this->format($left_flow);
        // $left = $res[0]['total_flow'] - $left_flow;
        // $left_fw = $this->format($left);
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['total_flow']=$total_flow.'G';
            $res[$key]['data'] = $used_flow.'G';
            $res[$key]['active_time']=date('Y-m-d H:i:s',$res[$key]['active_time']);
            $res[$key]['term_end_time']=date('Y-m-d H:i:s',$res[$key]['term_end_time']);
            $res[$key]['status'] = $res[$key]['status'];
            $res[$key]['left_flow'] = $left_fw.'G';

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
    }
    //判断卡可以充值什么类型套餐
    public function actionRechargeType(){
        $iccid = $this->get('iccid');
        $package_id = $this->get('package_id');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $cardresult = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);
        if($cardresult['term_end_time'] == '0'){
            $result['code'] = '1001';
            $result['msg']  = '首次充值请选择初始套餐';
            echo json_encode($result);
            exit;
        }elseif(time() < $cardresult['term_end_time']){
            $result['code'] = '1002';
            $result['msg'] = '您有初始套餐，请充值加油包';
            echo json_encode($result);
            exit;
        }elseif($cardresult['package_id'] == null && time() > $cardresult['term_end_time']){
            $result['code'] = '1003';
            $result['msg'] = '您的卡已过有效期，请重新充值初始套餐';
            echo json_encode($result);
            exit;
        }
    }
    public function format($flow){
        $body = $flow/1024/1024/1024;
        $left_f = floor($body*100)/100;
        return $left_f;
    }
    
    //根据iccid和套餐判断是否可以充值
    public function  actionRechargerTest(){
        $iccid = $this->get('iccid');
        $package_id = $this->get('package_id');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
            $iccids = substr($iccid, 8,-8);
        }else{
            $iccids = substr($iccid, 8,-7);
        }

        $cardresult = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $package = Package::findOne(['id'=>$cardresult['package_id']]);
        $packtype = Package::findOne(['id'=>$package_id]);
        $reserve = UserCardReserveRecharge::find()->andWhere(['card_id' => $cardresult['id']])->andWhere(['execute_status' => 2])->one();
        
        if($cardresult['package_id'] == null && time() > $cardresult['term_end_time']){
            if($packtype['type'] == '6'){
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
            if($packtype['type'] !='1'){
               $data['code'] = '1001';
               $data['msg'] = '首次充值请选择初始套餐!！';
               echo json_encode($data);
               exit; 
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
        }
        }elseif(time() < $cardresult['term_end_time']){
            if($package->length_unit == '12'){
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }
            if($packtype['type'] != '2'){
                $data['code'] = '1001';
                $data['msg'] = '您有初始套餐,请充值叠加包';
                echo json_encode($data);
                exit;
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
            }

        }elseif(time() > $cardresult['term_end_time']){
            if(!empty($reserve)){
                $data['code'] = '1001';
                $data['msg'] = '有未生效的预订购，请等待生效后再进行订购';
                echo json_encode($data);
                exit;
            }
            if($packtype['type'] !='1'){
               $data['code'] = '1001';
               $data['msg'] = '首次充值请选择初始套餐！';
               echo json_encode($data);
               exit; 
            }else{
                $data['code'] = '1002';
                $data['msg'] = '操作成功';
                echo json_encode($data);
                exit;
        }
        }
    }
    /**
     * 判断卡状态是否能充值
     */
    public function actionJudgeStatus(){
        $iccid = $this->get('iccid');
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $judge = Card::find()->where(['like','iccid',$iccid])->one();
        if(empty($judge)){
            $result['code'] = '0';
            $result['msg'] = '未找到卡，请检查是否填写正确！';
            echo json_encode($result);
        }else{
            if($judge->dgcs=='0'){
                $result['code'] = '0';
                $result['msg'] = '暂停新开卡业务，3月16日之后恢复！';
                echo json_encode($result);
                exit;
            }
            if($judge->status == 6){
                $result['code'] = '1';
                $result['msg'] = '卡已经失效，不能充值！';
                echo json_encode($result);
            }else{
                $result['code'] = '200';
                $result['msg'] = '卡可以正常充值';
                echo json_encode($result);
            }
        }
    }
    /**
     * get curl
     * @param $url
     * @return mixed
     */
    public function getUrl($url){
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        //$data = curl_exec($curl);
        $response = curl_exec($curl);

        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
            list($header, $body) = explode("\r\n\r\n", $response, 2);
        }
        //关闭URL请求
        curl_close($curl);
        //return json_decode($data,TRUE);
        return $body;
    }
}
